﻿#region Copyright
/// <copyright>
/// Copyright (c) 2008 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Text;

using Osh.Media;

namespace Osh.Qwerty
{
	public class Tree : MediaTree
	{
		public Tree(ChannelDatabase database, Guid id, string name, List<IMediaFolder> folders)
			: base(database, id.ToString(), name, folders)
		{
		}

		internal Guid Guid
		{
			get { return new Guid(base.Id); }
		}

		internal ChannelDatabase ChannelDatabase
		{
			get { return (ChannelDatabase)this.Library; }
		}

		public void Update(Tree newTree)
		{
			this.Name = newTree.Name;

			// Updates existing and adds new folders
			foreach(Folder newFolder in newTree.FolderList)
			{
				if(newFolder.ServerId == null)
					continue;

				Folder folder;
				if(TryGetFolderByServerId(newFolder.ServerId.Value, out folder))
				{
					folder.Update(newFolder);
				}
				else
				{
					this.FolderList.Add(newFolder);
				}
			}

			// Removes deleted folders
			for(int i = 0; i < this.FolderList.Count; i++)
			{
				Folder folder = (Folder)this.FolderList[i];
				if(folder.ServerId == null)
					continue;

				Folder newFolder;
				if(!newTree.TryGetFolderByServerId(folder.ServerId.Value, out newFolder))
				{
					this.FolderList.Remove(folder);
					i--;
				}
			}
		}

		private bool TryGetFolderByServerId(int serverId, out Folder folder)
		{
			foreach(Folder f in this.FolderList)
			{
				if(f.ServerId == serverId)
				{
					folder = f;
					return true;
				}
			}
			folder = null;
			return false;
		}

		internal void RemoveChannel(Channel channel)
		{
			foreach(Folder folder in this.FolderList)
				folder.Channels.Remove(channel);

		}
	}
}
